/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.amqp.rabbitmq.refresh;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.tianyun.cloud.amqp.rabbitmq.RabbitContainerBeanWrapper;
import org.tianyun.cloud.amqp.rabbitmq.configuration.RabbitMqProperties;
import org.tianyun.cloud.amqp.rabbitmq.factory.ManagedRabbitListenerContainerFactory;
import org.tianyun.cloud.config.refresh.smart.SmartScopeRefreshedEvent;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * RabbitContainerRefresher
 *
 * @author ebert_chan
 */
public class RabbitContainerRefresher implements ApplicationListener<SmartScopeRefreshedEvent>, ApplicationContextAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitContainerRefresher.class);

    private Map<String, RabbitContainerBeanWrapper> rabbitContainerRefreshWrapperCache;

    private ApplicationContext applicationContext;

    public RabbitContainerRefresher(List<RabbitContainerBeanWrapper> rabbitContainerBeanWrappers) {
        if (rabbitContainerBeanWrappers != null && !rabbitContainerBeanWrappers.isEmpty()) {
            rabbitContainerRefreshWrapperCache = rabbitContainerBeanWrappers.stream().collect(Collectors.toMap(RabbitContainerBeanWrapper::getRefreshKey, Function.identity()));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(SmartScopeRefreshedEvent event) {
        if (applicationContext == null || rabbitContainerRefreshWrapperCache == null) {
            return;
        }

        for (Map.Entry<String, RabbitContainerBeanWrapper> entry : rabbitContainerRefreshWrapperCache.entrySet()) {
            RabbitContainerBeanWrapper wrapper = entry.getValue();
            if (!event.isRefreshedKey(wrapper.getRefreshKey())) {
                return;
            }
            doRefresh(wrapper);
        }

    }

    private void doRefresh(RabbitContainerBeanWrapper wrapper) {
        try {
            RabbitMqProperties properties = (RabbitMqProperties) applicationContext.getBean(wrapper.getPropertyBeanName());
            ManagedRabbitListenerContainerFactory managedRabbitListenerContainerFactory = (ManagedRabbitListenerContainerFactory) applicationContext.getBean(wrapper.getContainerFactoryBeanName());
            managedRabbitListenerContainerFactory.refresh(properties);
        } catch (Exception e) {
            LOGGER.error("rabbit listener refresh failed. refreshKey: {}", wrapper.getRefreshKey(), e);
        }
    }

}
